<template>
	<view>
		<view class="border-bottom tn-mb-sm tn-pt-sm tn-pb-sm upload-container tn-flex">
			<view class="uplaod-item tn-flex items-center justify-center border-radius-10 bg-gray position-relative"
				v-if="props.thumbs && props.thumbs.length > 0" v-for="(item, index) in props.thumbs" :key="index">
				<image mode="aspectFill" :src="item" @click="previewImage(index)">
				</image>
				<tn-badge value="icon-close" bg-color="tn-red" text-color="tn-white"
					@click="delVideo(index)"></tn-badge>
			</view>
			<view class="uplaod-item tn-flex items-center justify-center border-radius-10 bg-gray"
				v-if="!props.thumbs || props.thumbs.length < 3" @click="uploadVideo">
				<tn-icon name="video-square" size="80rpx" color="#aaa" />
			</view>
		</view>
		<tn-modal ref="modalRef" />
	</view>
</template>

<script lang="ts" setup>
	import { ref } from 'vue';
	import type { TnModalInstance } from '@tuniao/tnui-vue3-uniapp';
	import { tip, uploadFile } from '@/util/util';

	const modalRef = ref<TnModalInstance>()
	const emit = defineEmits(['del', 'add'])
	interface Props {
		videos : Array<string>,
		thumbs : Array<string>,
	}

	const props = defineProps<Props>()

	const previewImage = (index : number) => {
		console.log(props.videos[index])
	}

	const delVideo = (index : number) => {
		modalRef.value?.showModal({
			title: '操作提示',
			content: '确认删除该视频吗',
			showCancel: true,
			cancel: () => { },
			confirm: () => {
				emit('del', index)
			}
		})
	}

	const uploadVideo = () => {
		uni.chooseMedia({
			count: 1,
			mediaType: ['video'],
			sizeType: ['compressed'],
			success: (res : any) => {
				console.log(res)
				if (res.tempFiles && res.tempFiles[0]) {
					let file = res.tempFiles[0]
					if (file.thumbTempFilePath) {
						uploadFile(file.thumbTempFilePath).then((image : any) => {
							emit('add', image, 'thumb')
						}).catch(err => {
							tip({ title: err })
						})
					} else {
						emit('add', '', 'thumb')
					}
					uploadFile(file.tempFilePath).then((video : any) => {
						emit('add', video, 'video')
					}).catch(err => {
						tip({ title: err })
					})
				}
			}
		})
	}
</script>

<style lang="scss">
	.upload-container {
		.uplaod-item {
			width: 33%;
			height: 200rpx;
			margin-right: 15rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.uplaod-item:nth-child(3) {
			margin-right: 0;
		}
	}
</style>